package com.ruoyi.web.controller.examine.buffet;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Buffet;
import com.ruoyi.common.core.domain.entity.BuffetExamine;
import com.ruoyi.common.core.domain.entity.BuffetExamineDetail;
import com.ruoyi.common.core.domain.entity.RestaurantGoods;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.BuffetExamineDetailService;
import com.ruoyi.system.service.BuffetExamineService;
import com.ruoyi.system.service.BuffetService;
import com.ruoyi.system.service.RestaurantGoodsService;
import com.ruoyi.system.service.resp.BuffetExamineDetailDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/examine/goods/buffet/detail")
public class BuffetExamineDetailController extends BaseController {
    @Resource
    private BuffetExamineDetailService buffetExamineDetailService;

    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @Resource
    private BuffetExamineService buffetExamineService;

    @Resource
    BuffetService buffetService;

    @Log(title = "自助餐质检明细", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(BuffetExamineDetail examinePlan) {
        List<BuffetExamineDetail> list = buffetExamineDetailService.selectList(examinePlan);
        return getDataTable(fillToDTO(list));
    }

    @Log(title = "自助餐质检", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BuffetExamineDetail examineDetail) {
        examineDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = buffetExamineDetailService.update(examineDetail);
        if (!result) {
            return error();
        }
        BuffetExamineDetail buffetExamineDetail = buffetExamineDetailService.selectById(examineDetail.getId());
        processExmaineStatus(buffetExamineDetail);
        return success();
    }

    @Log(title = "自助餐质检", businessType = BusinessType.UPDATE)
    @PostMapping("/bactchEdit")
    public AjaxResult bactchEdit(@RequestBody List<BuffetExamineDetail> examineDetails) {
        for (BuffetExamineDetail examineDetail : examineDetails) {
            examineDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            Boolean result = buffetExamineDetailService.update(examineDetail);
            if (!result) {
                return error();
            }
            BuffetExamineDetail buffetExamineDetail = buffetExamineDetailService.selectById(examineDetail.getId());
            processExmaineStatus(buffetExamineDetail);
        }
        return success();
    }

    private void processExmaineStatus(BuffetExamineDetail buffetExamineDetail) {
        if (buffetExamineDetail == null || buffetExamineDetail.getExamineId() == null) {
            return;
        }
        List<BuffetExamineDetail> details = buffetExamineDetailService.selectList(BuffetExamineDetail.builder()
                .examineId(buffetExamineDetail.getExamineId()).build());
        int successCnt = 0;
        int failCnt = 0;
        for (BuffetExamineDetail detail : details) {
            if ("是".equals(detail.getGoodsStatus()) && "是".equals(detail.getPlatesStatus())) {
                successCnt = successCnt + 1;
            } else if ("否".equals(detail.getGoodsStatus()) || "否".equals(detail.getPlatesStatus())) {
                failCnt = failCnt + 1;
            }
        }
        if (failCnt > 0) {
            BuffetExamine update = new BuffetExamine();
            update.setId(buffetExamineDetail.getExamineId());
            update.setStatus("质检不通过");
            update.setCheckTime(new Date());
            update.setInspector(SecurityUtils.getNickName());
            buffetExamineService.update(update);
            return;
        }
        if (successCnt == details.size()) {
            BuffetExamine update = new BuffetExamine();
            update.setId(buffetExamineDetail.getExamineId());
            update.setStatus("质检通过");
            update.setCheckTime(new Date());
            update.setInspector(SecurityUtils.getNickName());
            buffetExamineService.update(update);

            //todo 修改状态
            Buffet buffet = buffetService.selectById(update.getBuffetId());
            if (buffet != null) {
                if (StringUtils.isNotBlank(update.getArea())){
                    if (update.getArea().equals("一区")){
                        buffet.setExamineStatus("质检通过");
                        buffetService.update(buffet);
                    }
                    if (update.getArea().equals("二区")){
                        buffet.setExamineStatus("质检通过");
                        buffetService.update(buffet);
                    }
                }
            }
            return;
        }
        BuffetExamine update = new BuffetExamine();
        update.setId(buffetExamineDetail.getExamineId());
        update.setStatus("质检中");
        buffetExamineService.update(update);
    }

    private List<BuffetExamineDetailDTO> fillToDTO(List<BuffetExamineDetail> buffetExamineDetails) {
        PageInfo<BuffetExamineDetail> oldPage = new PageInfo<>(buffetExamineDetails);
        Page<BuffetExamineDetailDTO> newPage = new Page<>();
        newPage.setTotal(oldPage.getTotal());
        if (CollectionUtils.isEmpty(buffetExamineDetails)) {
            return newPage;
        }

        List<Long> goodsIds = buffetExamineDetails.stream().map(BuffetExamineDetail::getGoodsId).collect(Collectors.toList());
        List<RestaurantGoods> restaurantGoodsList = restaurantGoodsService.selectByIds(goodsIds);
        Map<Long, RestaurantGoods> restaurantGoodsMap;
        if (CollectionUtils.isEmpty(restaurantGoodsList)) {
            restaurantGoodsMap = new HashMap<>();
        } else {
            restaurantGoodsMap = restaurantGoodsList.stream().collect(Collectors.toMap(RestaurantGoods::getId, r -> r));
        }
        buffetExamineDetails.forEach(b -> {
            BuffetExamineDetailDTO buffetExamineDetailDTO = new BuffetExamineDetailDTO();
            buffetExamineDetailDTO.setId(b.getId());
            buffetExamineDetailDTO.setGoodsId(b.getGoodsId());
            buffetExamineDetailDTO.setGoodsName(Optional.ofNullable(restaurantGoodsMap.get(b.getGoodsId())).map(RestaurantGoods::getName).orElse(null));
            buffetExamineDetailDTO.setPlatesStatus(b.getPlatesStatus());
            buffetExamineDetailDTO.setGoodsStatus(b.getGoodsStatus());
            buffetExamineDetailDTO.setMakeBy(b.getMakeBy());
            buffetExamineDetailDTO.setCreateBy(b.getCreateBy());
            buffetExamineDetailDTO.setCreateTime(b.getCreateTime());
            buffetExamineDetailDTO.setUpdateBy(b.getUpdateBy());
            buffetExamineDetailDTO.setUpdateTime(b.getUpdateTime());
            buffetExamineDetailDTO.setRemark(b.getRemark());
            newPage.add(buffetExamineDetailDTO);
        });
        return newPage;
    }
}
